package com.bizmda.bizsip.app.config;

import com.bizmda.bizsip.common.BizException;
import com.bizmda.bizsip.config.SinkConfigMapping;
import com.bizmda.log.trace.RestTemplateTraceInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;

/**
 * @author 史正烨
 */
@Slf4j
@Configuration
public class AppConfiguration {
    @Value("${bizsip.config-path:#{null}}")
    private String configPath;
    @Value("${bizsip.rest.connection.connection-request-timeout:-1}")
    private int connectionRequestTimeout;
    @Value("${bizsip.rest.connection.connect-timeout:-1}")
    private int connectTimeout;
    @Value("${bizsip.rest.connection.read-timeout:-1}")
    private int readTimeout;
    @Value("${bizsip.rest.connection.max-total:10}")
    private int maxTotal;
    @Value("${bizsip.rest.connection.default-max-per-route:5}")
    private int defaultMaxPerRoute;

    @Bean
    public AppServiceMapping appServiceMapping() throws BizException {
        return new AppServiceMapping(this.configPath);
    }

    @Bean
    public SinkConfigMapping sinkConfigMapping() throws BizException {
        return new SinkConfigMapping(this.configPath);
    }

    @Bean
    public CheckRuleConfigMapping checkRuleConfigMapping() throws BizException {
        return new CheckRuleConfigMapping(this.configPath);
    }

    @Bean
    public ControlRuleConfigMapping controlRuleConfigMapping() throws BizException {
        return new ControlRuleConfigMapping(this.configPath);
    }

    @Bean
    public ControlRuleMetricConfigMapping controlRuleMetricConfigMapping() {
        return new ControlRuleMetricConfigMapping(this.configPath);
    }

    @Bean
    public HttpComponentsClientHttpRequestFactory bizsipHttpRequestFactory() {

        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory()).build();

        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
        // 设置最大连接池的数量
        connectionManager.setMaxTotal(this.maxTotal);
        // 每个主机的最大并发量，route是指域名。--对MaxTotal的细化
        connectionManager.setDefaultMaxPerRoute(this.defaultMaxPerRoute);

        RequestConfig requestConfig = RequestConfig.custom()
                // 数据返回超时时间
                .setSocketTimeout(this.readTimeout)
                // 连接超时时间
                .setConnectTimeout(this.connectTimeout)
                // 从连接池中获取连接的超时时间
                .setConnectionRequestTimeout(this.connectionRequestTimeout)
                .build();

        CloseableHttpClient closeableHttpClient = HttpClientBuilder.create()
                .setDefaultRequestConfig(requestConfig)
                .setConnectionManager(connectionManager)
                .build();

        HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory
                = new HttpComponentsClientHttpRequestFactory(closeableHttpClient);
        return httpComponentsClientHttpRequestFactory;
    }

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate()
    {
        RestTemplate restTemplate = new RestTemplate(bizsipHttpRequestFactory());
        log.info("RestTemplate调用增加日志跟踪能力拦截器");
        restTemplate.setInterceptors(Collections.singletonList(new RestTemplateTraceInterceptor()));
        return restTemplate;
    }
}
